//
//  RootViewController.m
//  Partner
//
//  Created by Zyf on 16/7/8.
//  Copyright © 2016年 lexiao. All rights reserved.
//

#import "RootViewController.h"
#import "AFNetworkTool.h"
#import <JPUSHService.h>
#import <UIView+SDAutoLayout.h>
#import <UMSocial.h>
#import "HyBridBridge.h"
#import "HybirdUrlHandler.h"
#import "FirstViewController.h"
#import "MacroDefinition.h"

@interface RootViewController () <HybridUrlHanlder>
{
    NSString *requestUrl;
    NSString *isMain;
}

@property (nonatomic, strong) HyBridBridge *hyBridBridge;
@property WebViewJavascriptBridge *bridge;
@end

@implementation RootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationController.navigationBar.hidden = YES;
    
    //******************************************************************
    //配置JPush
    [self addNotificationCenter];
    
    __autoreleasing NSMutableSet *tags = [NSMutableSet set];
    [tags addObject:@"ios"];
    
    [JPUSHService setTags:tags
                    alias:nil
         callbackSelector:@selector(tagsAliasCallback:tags:alias:)
                   target:self];
    
    //******************************************************************
    
    [self.view addSubview:self.webView];
    
    NSLog(@"---------------------------");
    
    
    self.webView.scrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshWebView)];
    
}

- (void)refreshWebView {
    [self.webView reload];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if ([USERDEFAULTS_GET(@"UpdateImage") isEqualToString:@"yes"]) {
        [self.webView reload];
        
        USERDEFAULTS_SET(@"no", @"UpdateImage");
    }
    
    if ([USERDEFAULTS_GET(@"OUT") isEqualToString:@"yes"]) {
        [self.webView reload];
        USERDEFAULTS_SET(@"no", @"OUT");
    }
}

- (void)registrationMessagePush {
    NSString *fighter_id = USERDEFAULTS_GET(@"userID");
    NSString *app_id = @"2";
    NSString *token = [JPUSHService registrationID];
    
    NSString *system_version = [NSString stringWithFormat:@"%.2f", [[[UIDevice currentDevice] systemVersion] floatValue]];
    NSString *device_version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
    [dic setValue:fighter_id forKey:@"fighter_id"];
    [dic setValue:app_id forKey:@"app_id"];
    [dic setValue:token forKey:@"jpush_token"];
    [dic setValue:system_version forKey:@"system_version"];
    [dic setValue:device_version forKey:@"device_version"];
    
    [AFNetworkTool JSONDataWithUrl:[NSString stringWithFormat:@"%@login/saveJPushRegId", FORMAL] withDic:dic success:^(id json) {
        NSLog(@"推送返回代码: %@", [NSString stringWithFormat:@"%@", json[@"code"]]);
        NSLog(@"推送返回信息: %@", [NSString stringWithFormat:@"%@", json[@"message"]]);
    } fail:^{
        NSLog(@"失败");
    }];
    
    NSLog(@"请求的地址:  %@", [NSString stringWithFormat:@"%@login/saveJPushRegId", FORMAL]);
    
}

#pragma mark -- 懒加载
- (UIWebView *)webView {
    if (!_webView) {
        _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height - 20)];
        _webView.scalesPageToFit = YES;
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:FORMAL]];
        _webView.delegate = self;
        [_webView loadRequest:request];
        
        NSString *ua = [_webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
        NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%@ lexiao", ua],@"UserAgent", nil];
        [[NSUserDefaults standardUserDefaults] registerDefaults:dict];
        
    }
    return _webView;
}

- (HyBridBridge *)hyBridBridge {
    if (!_hyBridBridge) {
        _hyBridBridge = [[HyBridBridge alloc] init];
    }
    return _hyBridBridge;
}

#pragma mark -- HybirdUrlHandler代理
- (NSArray *)actionNames {
    return nil;
}

- (BOOL)handleDictionAry:(NSDictionary *)dictionary callback:(HybridCallbackBlock)callbackBlock {
    NSString *actionTag = dictionary[@""];
    if ([actionTag isEqualToString:@""]) {
        
        
        return YES;
    }
    
    
    
    return NO;
}





#pragma mark -- WebView代理
- (void)webViewDidStartLoad:(UIWebView *)webView {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    NSString *currentUrl = webView.request.URL.absoluteString;
    NSLog(@"网页加载完毕 :%@", currentUrl);
    
    [self.webView.scrollView.mj_header endRefreshing];
    
    if (USERDEFAULTS_GET(@"userID") != nil) {
        [self registrationMessagePush];
    }

    
    if ([currentUrl containsString:@"index.html?l="] || [currentUrl containsString:@"logintrue.html"] || [currentUrl containsString:@"s=/Partner/Index/index.html"] || [currentUrl containsString:@"uploadAvatar"]) {
        return;
    }
    
    if ([currentUrl isEqualToString:FORMAL]) {
        NSLog(@"是首页2");
        return;
    }else {
        if ([currentUrl containsString:@"lx_target_self=true"]) {
            return;
        }
        
        NSLog(@"添加返回按钮");
        [self addBackButton];
    }
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSString *currentUrl = request.URL.absoluteString;
    
    NSLog(@"Root请求的地址: %@", request.URL.absoluteString);
    
    
    
    if ([currentUrl containsString:@"lx_target_self=true"] || [currentUrl containsString:@"logintrue.html"] || [currentUrl containsString:@"uploadAvatar"] || [currentUrl containsString:@"s=/Partner/Index/index.html"]) {
        return YES;
    }
    
    
    
    if ([currentUrl containsString:@"index.html?l="]) {
        //首页 携带加密过的用户ID
        
        NSArray *tempArr = [currentUrl componentsSeparatedByString:@"?"];
        NSArray *tempArr2;
        
        for (NSString *str in tempArr) {
            if ([str containsString:@"lx_close_when_open=ture"]) {
                tempArr2 = [str componentsSeparatedByString:@"&"];
            }
        }
        
        NSString *baseUserID = [tempArr2[0] substringFromIndex:2];
        
        
        NSData *jiemi = [[NSData alloc] initWithBase64EncodedString:baseUserID options:0];
        NSString *userID = [[NSString alloc] initWithData:jiemi encoding:NSUTF8StringEncoding];
        USERDEFAULTS_SET(userID, @"userID");
        
        return YES;
    }
    
    if ([currentUrl isEqualToString:FORMAL]) {
        return YES;
    }else {
        [self loadWebViewControllerWithString:request.URL.absoluteString];
        return NO;
    }
    
    
    
    return NO;
    
}

- (void)loadWebViewControllerWithString:(NSString *)string {
    FirstViewController *fvc = [[FirstViewController alloc] initWithUrlString:string];
    [self.navigationController pushViewController:fvc animated:YES];
}

- (void)addBackButton {
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 20, 44, 44)];
    button.backgroundColor = [UIColor clearColor];
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)buttonClick:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -- UMengSocial配置
- (void)setupButton {
    UIButton *button = [UIButton new];
    button.backgroundColor = [UIColor blueColor];
    [button setTitle:@"分享" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view sd_addSubviews:@[button]];
    
    button.sd_layout.widthIs(50).heightIs(30).centerYEqualToView(self.view).centerXEqualToView(self.view);
}

- (void)buttonClick {
    
    NSString *shareText = @"";
    UIImage *shareImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"image" ofType:@"jpg"]];
    
    
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"577f69cce0f55abe820007ad"
                                      shareText:shareText
                                     shareImage:shareImage
                                shareToSnsNames:@[UMShareToWechatSession, UMShareToWechatTimeline, UMShareToQQ, UMShareToQzone]
                                       delegate:self];
}

-(void)didSelectSocialPlatform:(NSString *)platformName withSocialData:(UMSocialData *)socialData {
    if (platformName == UMShareToWechatSession) {
        NSLog(@"分享到微信好友");
        socialData.shareText = @"分享到微信好友的文字内容";
        socialData.extConfig.title = @"微信好友";
        socialData.extConfig.wechatSessionData.url = @"http://www.baidu.com";
    }else if (platformName == UMShareToWechatTimeline){
        socialData.shareText = @"分享到微信朋友圈的文字内容";
        socialData.extConfig.title = @"微信朋友圈";
        socialData.extConfig.wechatTimelineData.url = @"http://news.baidu.com";
    }else if (platformName == UMShareToQQ) {
        NSLog(@"分享到QQ好友");
        socialData.shareText = @"分享到QQ好友的文字内容";
        socialData.extConfig.title = @"QQ好友";
        socialData.extConfig.qqData.url = @"http://image.baidu.com";
    }else if (platformName == UMShareToQzone) {
        NSLog(@"分享到QQ空间");
        socialData.shareText = @"分享到QQ空间的文字内容";
        socialData.extConfig.title = @"QQ空间";
        socialData.extConfig.qzoneData.url = @"http://map.baidu.com";
    }
}

- (void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response {
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}

#pragma mark -- JPush配置
- (void)tagsAliasCallback:(int)iResCode
                     tags:(NSSet *)tags
                    alias:(NSString *)alias {
    NSString *callbackString =
    [NSString stringWithFormat:@"%d, \ntags: %@, \nalias: %@\n", iResCode,
     [self logSet:tags], alias];
    
    NSLog(@"TagsAlias回调:%@", callbackString);
}

- (NSString *)logSet:(NSSet *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}

- (void)addNotificationCenter {
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidSetup:)
                          name:kJPFNetworkDidSetupNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidClose:)
                          name:kJPFNetworkDidCloseNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidRegister:)
                          name:kJPFNetworkDidRegisterNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidLogin:)
                          name:kJPFNetworkDidLoginNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidReceiveMessage:)
                          name:kJPFNetworkDidReceiveMessageNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(serviceError:)
                          name:kJPFServiceErrorNotification
                        object:nil];
}

- (void)networkDidSetup:(NSNotification *)notification {
    NSLog(@"已连接");
}

- (void)networkDidClose:(NSNotification *)notification {
    NSLog(@"未连接");
}

- (void)networkDidRegister:(NSNotification *)notification {
    NSLog(@"%@", [notification userInfo]);
    NSLog(@"已注册");
}

- (void)networkDidLogin:(NSNotification *)notification {
    NSLog(@"已登录");
    
    if ([JPUSHService registrationID]) {
        NSLog(@"%@", [JPUSHService registrationID]);
        NSLog(@"get RegistrationID");
    }
}

- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSString *title = [userInfo valueForKey:@"title"];
    NSString *content = [userInfo valueForKey:@"content"];
    NSDictionary *extra = [userInfo valueForKey:@"extras"];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    
    NSString *currentContent = [NSString
                                stringWithFormat:
                                @"收到自定义消息:%@\ntitle:%@\ncontent:%@\nextra:%@\n",
                                [NSDateFormatter localizedStringFromDate:[NSDate date]
                                                               dateStyle:NSDateFormatterNoStyle
                                                               timeStyle:NSDateFormatterMediumStyle],
                                title, content, [self logDic:extra]];
    NSLog(@"%@", currentContent);
    
    NSMutableArray *messageContents = [NSMutableArray array];
    [messageContents insertObject:currentContent atIndex:0];
    
    NSString *allContent = [NSString
                            stringWithFormat:@"%@收到消息:\n%@\nextra:%@",
                            [NSDateFormatter
                             localizedStringFromDate:[NSDate date]
                             dateStyle:NSDateFormatterNoStyle
                             timeStyle:NSDateFormatterMediumStyle],
                            [messageContents componentsJoinedByString:nil],
                            [self logDic:extra]];
    
    NSLog(@"%@", allContent);
}

- (void)serviceError:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    NSString *error = [userInfo valueForKey:@"error"];
    NSLog(@"%@", error);
}


- (NSString *)logDic:(NSDictionary *)dic {
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str =
    [NSPropertyListSerialization propertyListFromData:tempData
                                     mutabilityOption:NSPropertyListImmutable
                                               format:NULL
                                     errorDescription:NULL];
    return str;
}

- (void)dealloc {
    [self unObserveAllNotifications];
}

- (void)unObserveAllNotifications {
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter removeObserver:self
                             name:kJPFNetworkDidSetupNotification
                           object:nil];
    [defaultCenter removeObserver:self
                             name:kJPFNetworkDidCloseNotification
                           object:nil];
    [defaultCenter removeObserver:self
                             name:kJPFNetworkDidRegisterNotification
                           object:nil];
    [defaultCenter removeObserver:self
                             name:kJPFNetworkDidLoginNotification
                           object:nil];
    [defaultCenter removeObserver:self
                             name:kJPFNetworkDidReceiveMessageNotification
                           object:nil];
    [defaultCenter removeObserver:self
                             name:kJPFServiceErrorNotification
                           object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
